package com.itheima.tanhua.service;

import cn.hutool.core.collection.CollUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.itheima.tanhua.api.CommentApi;
import com.itheima.tanhua.api.FocusUserApi;
import com.itheima.tanhua.api.UserInfoApi;
import com.itheima.tanhua.api.VideoApi;
import com.itheima.tanhua.autoconfig.template.OssTemplate;
import com.itheima.tanhua.domain.UserInfo;
import com.itheima.tanhua.enums.CommentType;
import com.itheima.tanhua.enums.LogType;
import com.itheima.tanhua.exception.BusinessException;
import com.itheima.tanhua.mongo.Comment;
import com.itheima.tanhua.mongo.FocusUser;
import com.itheima.tanhua.mongo.Video;
import com.itheima.tanhua.utils.Constants;
import com.itheima.tanhua.utils.UserHolder;
import com.itheima.tanhua.vo.CommentVo;
import com.itheima.tanhua.vo.ErrorResult;
import com.itheima.tanhua.vo.PageResult;
import com.itheima.tanhua.vo.VideoVo;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Lff
 * @date 2022/4/3
 */
@Service
public class SmallVideosService {

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private FastFileStorageClient client;

    @Autowired
    private FdfsWebServer webServer;

    @DubboReference
    private FocusUserApi focusUserApi;

    @DubboReference
    private VideoApi videoApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private RedisTemplate redisTemplate;

    @DubboReference
    private CommentApi commentApi;

    @Autowired
    private UserFreezeService userFreezeService;

    @Autowired
    private MqMessageService mq;

    /**
     * 视频上传
     *
     * @param videoThumbnail 封面图
     * @param videoFile      视频文件
     */
    @CacheEvict(value = "videosList", allEntries = true)
    public void uploadVideos(MultipartFile videoThumbnail, MultipartFile videoFile) {
        //检查用户状态
        userFreezeService.checkUserStatus("3", UserHolder.getUser().getId());
        if (videoFile == null || videoThumbnail == null) {
            throw new BusinessException(ErrorResult.error());
        }
        //将图片上传到阿里云
        String imgPath = "";
        StorePath storePath = null;
        try {
            imgPath = ossTemplate.upload(videoThumbnail.getOriginalFilename(),
                    videoThumbnail.getInputStream());
            //将视频文件上传到FastDfs
            String originalFilename = videoFile.getOriginalFilename();
            String fileName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            //参数一 输出流 参数二，文件的长度 参数三：文件后缀
            storePath = client.uploadFile(videoFile.getInputStream(),
                    videoFile.getSize(), fileName, null);
        } catch (IOException e) {
            throw new BusinessException(ErrorResult.error());
        }
        //将两个文件的存储路径构建到Videos实体中
        Video video = new Video();
        //拼接路径 视频存储地址
        video.setVideoUrl(webServer.getWebServerUrl() + storePath.getFullPath());
        //封面地址
        video.setPicUrl(imgPath);
        video.setUserId(UserHolder.getUser().getId());
        video.setCreated(System.currentTimeMillis());
        UserInfo user = userInfoApi.findById(UserHolder.getUser().getId());
        video.setText("用户" + user.getNickname() + "的动态");
        //保存实体
        String id = videoApi.save(video);
        if (StringUtils.isEmpty(id)) {
            throw new BusinessException(ErrorResult.error());
        }
    }


    /**
     * 从缓存中拿去vid
     * <p>
     * 有 --> 根据vid查询
     * <p>
     * 没有 --> 查询当前最新数据
     *
     * @param page
     * @param pagesize
     * @return
     */
    @Cacheable(value = "videosList", key = "'user_' +" +
            " T(com.itheima.tanhua.utils.UserHolder).getUser().id" +
            "+'_'+#page+'_'+#pagesize")
    public PageResult findVideosList(Integer page, Integer pagesize) {
        //查询缓存中是否有数据
        String vidStr = (String) redisTemplate.opsForValue().get(Constants.VIDEOS_RECOMMEND + UserHolder.getUser().getId());
        PageResult pr = new PageResult();
        List<Long> vidList = null;
        if (!StringUtils.isEmpty(vidStr)) {
            //没有 查询最新的数据记录
            String[] vids = vidStr.split(",");
            //计算起始位置
            int start = (page - 1) * pagesize;
            if (start < vids.length) {
                vidList = Arrays.stream(vids).skip(start)
                        .limit(pagesize).map(id -> Long.valueOf(id))
                        .collect(Collectors.toList());
            }
        }
        //查询
        List<Video> videos = videoApi.getRecommendVideoList(vidList, page, pagesize);
        if (CollUtil.isEmpty(videos)) {
            return new PageResult();
        }
        //抽取id
        List<Long> ids = CollUtil.getFieldValues(videos, "userId", Long.class);
        //查询user信息
        Map<Long, UserInfo> userMap = userInfoApi.getUserInfosToMap(ids, null);
        List<VideoVo> videoVos = new ArrayList<>();
        //初始化返回对象
        for (Video video : videos) {
            UserInfo userInfo = userMap.get(video.getUserId());
            if (userInfo != null) {
                VideoVo init = VideoVo.init(userInfo, video);
                String key = Constants.FOCUS_USER;
                String hashKey = Constants.FOCUS_USER + "_" + UserHolder.getUser().getId()
                        + "_" + video.getUserId();
                if (redisTemplate.opsForHash().hasKey(key, hashKey)) {
                    init.setHasFocus(1);
                }
                videoVos.add(init);
            }
        }
        //填充数据
        pr.setItems(videoVos);
        return pr;
    }

    /**
     * 发布评论
     *
     * @param id
     * @param comment
     */
    public Integer publishVideoComments(String id, String comment) {
        //获取当前登录用户的id
        Long userId = UserHolder.getUser().getId();
        //填充comments对象
        Comment c = new Comment();
        c.setUserId(userId);
        c.setPublishId(new ObjectId(id));
        c.setContent(comment);
        c.setCreated(System.currentTimeMillis());
        c.setCommentType(CommentType.VIDEO_COMMENT.getType());
        //进行保存
        Integer count = videoApi.publishAll(c);
        return count;
    }

    /**
     * 视频点赞
     *
     * @param id
     * @return
     */
    public Integer videoLike(String id) {
        Comment comment = new Comment();
        comment.setCommentType(CommentType.VIDEO_LIKE.getType());
        comment.setCreated(System.currentTimeMillis());
        comment.setUserId(UserHolder.getUser().getId());
        comment.setPublishId(new ObjectId(id));
        Integer integer = videoApi.publishAll(comment);
        //保存到redis中
        String key = Constants.VIDEO_INTERACT_KEY + id;
        String hashKey = Constants.VIDEO_LIKE_HASHKEY + UserHolder.getUser().getId();
        redisTemplate.opsForHash().put(key, hashKey, "1");
        //发送mq
        mq.sendLogMessage(UserHolder.getUser().getId(), LogType.LOG_TYPE_LIKE_VIDEO.getValue(),
                "video", id);
        return integer;
    }


    /**
     * 视频取消点赞
     *
     * @param id
     * @return
     */
    public Integer videoDisLike(String id) {
        Comment comment = new Comment();
        comment.setCommentType(CommentType.VIDEO_LIKE.getType());
        comment.setUserId(UserHolder.getUser().getId());
        comment.setPublishId(new ObjectId(id));
        Integer integer = videoApi.removeAll(comment);
        //清除缓存从redis中
        String key = Constants.VIDEO_INTERACT_KEY + id;
        String hashKey = Constants.VIDEO_LIKE_HASHKEY + UserHolder.getUser().getId();
        redisTemplate.opsForHash().delete(key, hashKey);
        return integer;
    }


    /**
     * 查询所有的视频评论
     *
     * @param videoId
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult findAllVideoComments(String videoId, Integer page, Integer pagesize) {
        List<Comment> list = commentApi.findCommentAll(videoId, CommentType.VIDEO_COMMENT, page, pagesize);
        if (CollUtil.isEmpty(list)) {
            return new PageResult();
        }
        //收取id
        List<Long> ids = CollUtil.getFieldValues(list, "userId", Long.class);
        Map<Long, UserInfo> userMap = userInfoApi.getUserInfosToMap(ids, null);
        List<CommentVo> result = new ArrayList<>();
        for (Comment comment : list) {
            UserInfo userInfo = userMap.get(comment.getUserId());
            if (userInfo != null) {
                CommentVo init = CommentVo.init(userInfo, comment);
                if (checkUserIsLike(comment.getId().toHexString(), UserHolder.getUser().getId())) {
                    //已经点赞
                    init.setHasLiked(1);
                }
                result.add(init);
            }
        }
        return new PageResult(page, pagesize, 0l, result);
    }

    /**
     * 视频评论点赞
     *
     * @param videoId
     * @return
     */
    public Integer likeComment(String videoId) {
        //获取当前用户id
        Long userId = UserHolder.getUser().getId();
        //判断用户是否点赞
        if (checkUserIsLike(videoId, userId)) {
            throw new BusinessException(ErrorResult.likeCommentError());
        }
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(videoId));
        comment.setUserId(userId);
        comment.setCommentType(CommentType.VIDEO_COMMENT_LIKE.getType());
        comment.setCreated(System.currentTimeMillis());
        //保存点赞
        commentApi.saveComment(comment);
        //更新评论点赞数
        comment.setId(comment.getPublishId());
        int count = commentApi.updateCommentLikeCount(comment);
        //存到redis
        String key = Constants.VIDEO_COMMENT_LIKE + videoId;
        String hashKey = Constants.VIDEO_COMMENT_LIKE_HASHKEY + userId.toString();
        redisTemplate.opsForHash().put(key, hashKey, "1");
        return count;
    }

    /**
     * 校验用户是否点赞
     *
     * @param videoId
     * @param userId
     * @return
     */
    private boolean checkUserIsLike(String videoId, Long userId) {
        String key = Constants.VIDEO_COMMENT_LIKE + videoId;
        String hashKey = Constants.VIDEO_COMMENT_LIKE_HASHKEY + userId.toString();
        if (redisTemplate.opsForHash().hasKey(key, hashKey)) {
            //缓存里有，返回ture
            return true;
        }
        if (commentApi.hasComment(videoId, userId, CommentType.VIDEO_COMMENT_LIKE)) {
            //查询数据库，有就添加缓存记录
            redisTemplate.opsForHash().put(key, hashKey, "1");
            return true;
        }
        return false;
    }

    /**
     * 取消视频评论点赞
     *
     * @param videoId
     * @return
     */
    public Integer disLikeComment(String videoId) {
        //获取当前用户id
        Long userId = UserHolder.getUser().getId();
        //判断用户是否点赞
        if (!checkUserIsLike(videoId, userId)) {
            throw new BusinessException(ErrorResult.disLikeCommentError());
        }
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(videoId));
        comment.setUserId(userId);
        comment.setCommentType(CommentType.VIDEO_COMMENT_LIKE.getType());
        comment.setCreated(System.currentTimeMillis());
        //保存点赞
        commentApi.delComment(comment);
        //更新评论点赞数
        comment.setId(comment.getPublishId());
        int count = commentApi.updateCommentLikeCountRm(comment);
        //清除redis
        String key = Constants.VIDEO_COMMENT_LIKE + videoId;
        String hashKey = Constants.VIDEO_COMMENT_LIKE_HASHKEY + userId.toString();
        redisTemplate.opsForHash().delete(key, hashKey);
        return count;
    }

    /**
     * 关注
     *
     * @param followUserId
     */

    public void toUserFocus(Long followUserId) {
        //获取用户id
        Long userId = UserHolder.getUser().getId();
        //查看是否保存过
        if (checkFocus(userId, followUserId)) {
            throw new BusinessException(ErrorResult.focusUserError());
        }
        //构建UserFocus
        FocusUser focusUser = new FocusUser();
        focusUser.setUserId(userId);
        focusUser.setFollowUserId(followUserId);
        focusUser.setCreated(System.currentTimeMillis());
        //调用api保存
        String id = focusUserApi.save(focusUser);
        if (StringUtils.isEmpty(id)) {
            throw new BusinessException(ErrorResult.error());
        }
        String key = Constants.FOCUS_USER;
        String hashKey = Constants.FOCUS_USER + "_" + userId
                + "_" + followUserId;
        redisTemplate.opsForHash().put(key, hashKey, "1");
    }

    private boolean checkFocus(Long userId, Long followUserId) {
        //看看redis中是否关注
        String key = Constants.FOCUS_USER;
        String hashKey = Constants.FOCUS_USER + "_" + userId.toString()
                + "_" + followUserId.toString();
        if (redisTemplate.opsForHash().hasKey(key, hashKey)) {
            return true;
        }
        if (focusUserApi.hasFocus(userId, followUserId)) {
            //存到redis中
            redisTemplate.opsForHash().put(key, hashKey, "1");
            return true;
        }
        return false;
    }

    /**
     * 取关
     *
     * @param followUserId
     */
    public void toUserUnFocus(Long followUserId) {
        //获取用户id
        Long userId = UserHolder.getUser().getId();
        //查看是否保存过
        if (!checkFocus(userId, followUserId)) {
            throw new BusinessException(ErrorResult.unFocusUserError());
        }
        //调用api删除
        boolean b = focusUserApi.delete(userId, followUserId);
        if (!b) {
            throw new BusinessException(ErrorResult.error());
        }
        String key = Constants.FOCUS_USER;
        String hashKey = Constants.FOCUS_USER + "_" + userId
                + "_" + followUserId;
        redisTemplate.opsForHash().delete(key, hashKey);
    }
}
